//
//  GYComposeViewController.swift
//  Weibo
//
//  Created by vane on 16/8/17.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class GYComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    private func setupUI(){
        
        view.backgroundColor = RandomColor()
        
        setupNav()
        
        view.addSubview(composeTextView)
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        view.addSubview(composeBottomView)
        
        composeBottomView.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
        
        composeTextView.addSubview(composePictureView)
        
        composePictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(composeTextView)
        }

        composeBottomView.closure = {[weak self] (type: GYComposeBottomViewType)->() in
            
            switch type{
                
            case .Picture:
                print("涂片")
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("☺")
                self?.switchKeyboard()
                
            case .Add:
                print("+")
                
            }
        }
        composePictureView.closure = { [weak self] in
        
            self?.selectImages()
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    func keyboardWillChangeFrame(noti:NSNotification){
        
//      print(noti)
        
        guard let duration = noti.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double else{
            return
        }

        guard let rect = noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else{
            return
        }

        let newRect = rect.CGRectValue()

        composeBottomView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }

    }
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
    @objc private func cancelAction(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendAction(){
        
        print("发布微博")
        
        if composePictureView.imageList.count == 0{
            
            update()
        }else{
            
            upload()
               }
    }
    
     private func update(){
        AFNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
            self.cancelAction()
            
            NSNotificationCenter.defaultCenter().postNotificationName("send", object: nil)
            
            
            }) { (error) -> () in
                
                SVProgressHUD.showErrorWithStatus("发布失败")
                
        }
    }
    private func upload(){
        AFNetworkTools.sharedTools.composeUpload(composeTextView.text, images: composePictureView.imageList, success: { (response) -> () in
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
            NSNotificationCenter.defaultCenter().postNotificationName("send", object: nil)
            
            self.cancelAction()
            
            }) { (error) -> () in
                
                //                print(error)
                SVProgressHUD.showErrorWithStatus("发布失败")
                
        }
    }


    private lazy var titleView:UILabel = {
        
        let lab = UILabel()
        
        let name = GYUserAccountViewModel.sharedTools.userAccount!.screen_name!
        
        let str = "发微博\n\(name)"
        // 初始化一个富文本
        let attr = NSMutableAttributedString(string: str)
        
        let range = (str as NSString).rangeOfString(name)
        
        attr.addAttributes([NSForegroundColorAttributeName:AppThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        lab.attributedText = attr
        
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.font = UIFont.systemFontOfSize(16)
        lab.sizeToFit()
        
        return lab
        
    }()
    
    private lazy var composeTextView : GYComposeTextView = {
    
        let comp = GYComposeTextView()
    
        comp.font = UIFont.systemFontOfSize(16)
        
        comp.placeholder = "独孤九剑一剑"
        
        comp.alwaysBounceVertical = true
        
        comp.delegate = self
        
    return comp
    }()
    
    private lazy var composeBottomView:GYComposeBottomView = GYComposeBottomView()
    
    private lazy var composePictureView: GYComposePictureView = GYComposePictureView()
    
    private lazy var emoticonKeyboardView:GYEmoticonKeyboardView = GYEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
}

extension GYComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 取消键盘第一响应
        self.composeTextView.resignFirstResponder()
    }
}
extension GYComposeViewController{
    
    func selectImages(){
        
        let pickerVc = UIImagePickerController()
        
        pickerVc.delegate = self
        
        presentViewController(pickerVc, animated: true, completion: nil)
        
    }
    func switchKeyboard(){
        
        if composeTextView.inputView == nil {
        
            composeTextView.inputView = emoticonKeyboardView
            
            composeBottomView.isEmoticon = true

            
        }else{
            
            composeTextView.inputView = nil
            
            composeBottomView.isEmoticon = false

        }
        
        composeTextView.reloadInputViews()
        
        composeTextView.becomeFirstResponder()

        
    }
    
}
extension GYComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
//        print(info)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        composePictureView.addImages(UIImage.dealImageScale(image, width: 600))
        
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        
        dismissViewControllerAnimated(true, completion: nil)
    }


}

